import {
    smartMathsBulkDeletes,
    smartMathsCreate,
    smartMathsIsFavorited,
    smartMathsPagination,
    smartMathsQueryAnswer,
    smartMathsUpdate,
  } from '@/services/swagger/smartMaths';
  import { HeartFilled, HeartOutlined, PlusOutlined } from '@ant-design/icons';
  import type { ActionType, ProColumns } from '@ant-design/pro-components';
  import {
    FooterToolbar,
    ModalForm,
    PageContainer,
    ProFormText,
    ProTable,
  } from '@ant-design/pro-components';
  import { FormattedMessage, useIntl } from '@umijs/max';
  import { Button, message, Modal, Select } from 'antd';
  import React, { useRef, useState } from 'react';
  
  /**
   * @en-US Add
   * @zh-CN 添加
   * @param fields
   */
  const handleAdd = async (fields: API.QuestionCreateInputModel) => {
    const hide = message.loading('正在添加');
    try {
      await smartMathsCreate({ ...fields });
      hide();
      message.success('添加成功');
      return true;
    } catch (error) {
      hide();
      message.error('添加失败, 请再次重试!');
      return false;
    }
  };
  
  /**
   * @en-US Update  status
   * @zh-CN 修改状态
   * @param fields
   */
  const handleStatus = async (id: number, status: number) => {
    const hide = message.loading('正在修改');
    try {
      await smartMathsUpdate({ id: id, status: status as API.MathQuestionStatus });
      hide();
      message.success('修改成功');
      return true;
    } catch (error) {
      hide();
      message.error('修改失败, 请再次重试!');
      return false;
    }
  };
  
  /**
   * @en-US Toggle favorite
   * @zh-CN 是否收藏
   * @param fields
   */
  const handleToggleFavorite = async (fields: API.QuestionOutputModel) => {
    const hide = message.loading('正在修改');
    try {
      await smartMathsIsFavorited({ id: fields.id as number });
      hide();
      if (fields.isFavorited) {
        message.success('取消收藏');
      } else {
        message.success('收藏成功');
      }
      return true;
    } catch (error) {
      hide();
      message.error('修改失败, 请再次重试!');
      return false;
    }
  };
  
  /**
   *  Delete
   * @zh-CN 删除
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows: API.QuestionOutputModel[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      const ids = {
        ids: selectedRows.map((row) => row.id).join(','), // 示例 ID 列表
      } as API.SmartMathsBulkDeletesParams;
  
      await smartMathsBulkDeletes(ids);
      hide();
      message.success('删除成功');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败, 请再次重试！');
      return false;
    }
  };
  
  const TableList: React.FC = () => {
    /**
     * @en-US Pop-up window of new window
     * @zh-CN 新建窗口的弹窗
     *  */
    const [createModalOpen, handleModalOpen] = useState<boolean>(false);
    /**
     * @en-US The pop-up window of the distribution update window
     * @zh-CN 分布更新窗口的弹窗
     * */
    const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  
    const [showDetail, setShowDetail] = useState<boolean>(false);
  
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<API.QuestionOutputModel>();
    const [selectedRowsState, setSelectedRows] = useState<API.QuestionOutputModel[]>([]);
  
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [modalContent, setModalContent] = useState('');
  
    /**
     * @en-US Fetch Answer
     * @zh-CN 获取答案
     * */
    const fetchAnswer = async (questionId: number) => {
      try {
        const answer = await smartMathsQueryAnswer({ id: questionId });
        setModalContent(answer.data as string);
        setIsModalVisible(true);
      } catch (error) {
        message.error('获取答案失败'); // 错误处理
      }
    };
  
    /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
    const intl = useIntl();
  
    const columns: ProColumns<API.QuestionOutputModel>[] = [
      {
        title: (
          <FormattedMessage
            id="pages.searchTable.updateForm.question.questionLabel"
            defaultMessage="Question"
          />
        ),
        dataIndex: 'question',
        render: (dom, entity) => {
          return (
            <a
              onClick={() => {
                fetchAnswer(entity.id as number);
              }}
            >
              {dom}
            </a>
          );
        },
      },
      {
        title: (
          <FormattedMessage
            id="pages.searchTable.updateForm.isFavorited.favoritedLabel"
            defaultMessage="Is favorited"
          />
        ),
        dataIndex: 'isFavorited',
        valueType: 'select',
        valueEnum: {
          true: { text: '收藏' },
          false: { text: '未收藏' },
        },
        render: (text, entity) => {
          return (
            <a
              onClick={() => {
                handleToggleFavorite(entity);
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }}
            >
              {entity.isFavorited ? <HeartFilled style={{ color: 'red' }} /> : <HeartOutlined />}
            </a>
          );
        },
        renderFormItem: (item, { defaultRender, ...rest }, form) => {
          return <Select {...rest} placeholder="请选择"></Select>;
        },
      },
      {
        title: <FormattedMessage id="pages.searchTable.titleStatus" defaultMessage="Status" />,
        dataIndex: 'Status',
        valueType: 'select',
        valueEnum: {
          0: { text: '待查看' },
          1: { text: '已解决' },
          2: { text: '未解决' },
        },
        render: (text, entity) => {
          return (
            <Select
              value={Number(entity.status)} // 确保将text转为数字
              onChange={(value) => {
                handleStatus(entity.id as number, value as number);
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }}
              placeholder="Select status" // 可以添加一个占位符
            >
              <Select.Option value={0}>
                <FormattedMessage
                  id="pages.searchTable.status.pendingReview"
                  defaultMessage="Pending Review"
                />
              </Select.Option>
              <Select.Option value={1}>
                <FormattedMessage id="pages.searchTable.status.resolved" defaultMessage="Resolved" />
              </Select.Option>
              <Select.Option value={2}>
                <FormattedMessage
                  id="pages.searchTable.status.unresolved"
                  defaultMessage="Unresolved"
                />
              </Select.Option>
            </Select>
          );
        },
        renderFormItem: (item, { defaultRender, ...rest }, form) => {
          return <Select {...rest} placeholder="请选择"></Select>;
        },
      },
      {
        title: <FormattedMessage id="pages.searchTable.created" defaultMessage="Created time" />,
        sorter: true,
        dataIndex: 'created',
        valueType: 'dateTime',
        search: false,
      },
    ];
    return (
      <PageContainer>
        <ProTable<API.ChineseDictionaryOutputModel, API.SmartDictionariesPaginationParams>
          headerTitle={intl.formatMessage({
            id: 'pages.searchTable.question.list',
            defaultMessage: 'Question list',
          })}
          actionRef={actionRef}
          rowKey="id"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                handleModalOpen(true);
              }}
            >
              <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
            </Button>,
          ]}
          request={smartMathsPagination}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />
        {selectedRowsState?.length > 0 && (
          <FooterToolbar
            extra={
              <div>
                <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
                <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
                <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
              </div>
            }
          >
            <Button
              onClick={async () => {
                await handleRemove(selectedRowsState);
                setSelectedRows([]);
                actionRef.current?.reloadAndRest?.();
              }}
            >
              <FormattedMessage
                id="pages.searchTable.batchDeletion"
                defaultMessage="Batch deletion"
              />
            </Button>
          </FooterToolbar>
        )}
        <ModalForm
          title={intl.formatMessage({
            id: 'pages.searchTable.createForm.newQuestion',
            defaultMessage: 'New Question',
          })}
          width="400px"
          open={createModalOpen}
          onOpenChange={handleModalOpen}
          onFinish={async (value) => {
            const success = await handleAdd(value as API.QuestionCreateInputModel);
            if (success) {
              handleModalOpen(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
        >
          <ProFormText
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="pages.searchTable.question"
                    defaultMessage="Question is required"
                  />
                ),
              },
            ]}
            width="md"
            name="question"
          />
        </ModalForm>
        <Modal
          title={<FormattedMessage id="pages.searchTable.answer" defaultMessage="Answer" />}
          visible={isModalVisible}
          onCancel={() => setIsModalVisible(false)}
          footer={null} // 可以根据需要定义底部按钮
        >
          <div dangerouslySetInnerHTML={{ __html: modalContent }} />
        </Modal>
      </PageContainer>
    );
  };
  
  export default TableList;
  